﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using TestForm.entity;
using YbxLibrary;
using YbxLibrary.entity;
using YbxLibrary.entity.indata;
using YbxLibrary.entity.outdata;

namespace TestForm
{
    public partial class Form1 : Form
    {
        public static string dbPath = "api.db";

        public Form1()
        {
            InitializeComponent();
        }


        private static string formatJson(String str)
        {
            if (IsValidJson(str))
            {
               // return JsonConvert.SerializeObject(str, Formatting.Indented);
                // 解析JSON字符串
                var jsonParsed = JToken.Parse(str);
                // 格式化JSON字符串
                return jsonParsed.ToString(Formatting.Indented);
            }
            else
            {
                return str;
            }
        }


        public static string GetNameValueFromJson(string jsonString)
        {
            JObject json = JObject.Parse(jsonString);
            JToken nameToken = json["infno"];
            if (nameToken != null && !nameToken.HasValues)
            {
                return nameToken.ToString();
            }
            else
            {
                return "";
               // throw new ArgumentException("JSON 中未找到 'name' 节点或其值无效。");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox3.Text = "";
            YbEntity ybEntity = null;
            string infno = GetNameValueFromJson(textBox1.Text);

            textBox1.Text = formatJson(textBox1.Text);

            if (infno != "")
            {
                ybEntity = CallYb.YhHbCall(textBox2.Text, textBox1.Text, "org");
            }
            else 
            {
                ybEntity = CallYb.YhHbCall(textBox2.Text, textBox1.Text, "", "", this.textBox4.Text, this.textBox5.Text, "");
            }

            if (ybEntity != null)
            {
                if (infno != "")
                {
                    textBox3.Text = ybEntity.astr_jysc;               
                }
                else 
                {
                    if (ybEntity.infcode != 0)
                    {
                        textBox3.Text = ybEntity.astr_jysc;
                    }
                    else
                    {
                        String str = ybEntity.output;
                        textBox3.Text = str == "" ? ybEntity.astr_jysc : str;
                    }
                } 
            }
            textBox3.Text = formatJson(textBox3.Text);
        }

       /// <summary>
       /// 读卡操作输入输出处理
       /// </summary>
        private  void read_card_demo()
        {
            // 入参data
            String t1101in = JsonUtils.ObjectToJson<T1101in>(new T1101in("03", "420325199109067018"));
            // 调用医保dll返回值
            YbEntity ybEntity = CallYb.YhHbCall(T1101in.JYBH, t1101in, "", "", this.textBox4.Text, this.textBox5.Text, "");
            String msg = ybEntity.infcode != 0 ? ybEntity.err_msg : ybEntity.output;
            if (ybEntity.infcode != 0)
            {
                MessageBox.Show(ybEntity.err_msg);
            }
            else
            {
                T1101out t1101Out = JsonUtils.JsonToObject<T1101out>(ybEntity.output);
                String str = t1101Out.baseinfo.certno;
                MessageBox.Show(str);
            }
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            this.textBox1.Text = @"{
    ""data"": {
        ""begntime"": """",
        ""card_sn"": """",
        ""certno"": """",
        ""mdtrt_cert_no"": ""420325199109067018"",
        ""mdtrt_cert_type"": ""02"",
        ""psn_cert_type"": """",
        ""psn_name"": """"
    }
}";
            this.textBox2.Text = "1101";
            this.textBox3.Text = "";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DbMana dbMana = new DbMana();
            dbMana.ShowDialog();
        }

        private static List<InterfaceInfo> selectInterface(string jybh)
        {
            List<InterfaceInfo> item = new List<InterfaceInfo>();
            using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath + ";Version=3;"))
            {
                connection.Open();
                string selectSql = "";
                if (jybh == "")
                {
                    selectSql = "select * from interface_info where 1=1 or infno = @infno";
                }
                else
                {
                    selectSql = "select * from interface_info where infno = @infno";
                }
                SQLiteCommand selectCmd = new SQLiteCommand(selectSql, connection);
                selectCmd.Parameters.AddWithValue("@infno", jybh);
                using (SQLiteDataReader reader = selectCmd.ExecuteReader())
                {
                    InterfaceInfo interfaceInfo = null;
                    while (reader.Read())
                    {
                        interfaceInfo = new InterfaceInfo();
                        interfaceInfo.id = reader.GetInt32(0);
                        interfaceInfo.infno = reader.GetInt32(1);
                        interfaceInfo.input = reader.GetString(2);
                        interfaceInfo.output = reader.GetString(3);
                        interfaceInfo.desc = reader.GetString(4);
                        item.Add(interfaceInfo);
                    }
                    connection.Close();
                }
            }
            return item;
        }

        public static bool IsValidJson(string jsonString)
        {
            try
            {
                JToken.Parse(jsonString);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        private void textBox2_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                List<InterfaceInfo> items = selectInterface(textBox2.Text);
                if (items != null && items.Count > 0)
                {
                    String jsonStr_in =  items.First().input;
                    String jsonStr_out = items.First().output;
                    bool str = IsValidJson(jsonStr_in);
                    if (str)
                    {
                        this.textBox1.Text = formatJson(jsonStr_in);
                    }
                    else 
                    {
                        MessageBox.Show("输入json字符串不合法！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.textBox1.Text = jsonStr_in;
                    }

                    bool str_out = IsValidJson(jsonStr_out);
                    if (str_out)
                    {
                        this.textBox3.Text = formatJson(jsonStr_out);
                    }
                    else
                    {
                        MessageBox.Show("输出json字符串不合法！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.textBox3.Text = jsonStr_out;
                    }
                }
                else
                {
                    MessageBox.Show("未维护此接口！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.textBox1.Text = "";
                    this.textBox3.Text = "";
                }
            }
        }
    }
}
